import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

export class CreateThreeScene {
  updates = new Map()
  scene = new THREE.Scene()
  renderer = new THREE.WebGLRenderer()
	constructor(id, options = {}) {
		const element = document.querySelector(id)
		const { width, height } = element.getBoundingClientRect()
		this.renderer.setSize(width, height)
		this.camera = new THREE.PerspectiveCamera(45, width / height, 1, 100)
		element.appendChild(this.renderer.domElement)
		if (options.camera) {
			const { x, y, z } = { ...this.camera.position, ...options.camera }
			this.camera.position.set(x, y, z)
		}
		if (options.controls) {
			this.controls = new OrbitControls(this.camera, this.renderer.domElement)
			for (let key in options.controls) {
				this.controls[key] = options.controls[key]
			}
			this.controls.update()
		}
		this.animate()
	}
	add({ update, mesh, id }) {
		this.scene.add(mesh)
    if (update && id) {
      this.updates.set(id, update)
    }
	}
  remove(id) {
    this.updates.delete(id)
    this.scene.remove(this.scene.children.find(child => child.id === id))
  }
	animate() {
		requestAnimationFrame(this.animate.bind(this))
    for (let update of this.updates.values()) {
      update()
    }
		this.renderer.render(this.scene, this.camera)
	}
}
